<!-- eslint-disable vue/no-deprecated-v-on-native-modifier -->
<script setup>
import { ref, onMounted, toRaw } from 'vue';
import L from 'leaflet';
import 'leaflet-ant-path';//用于路径规划
import axios from 'axios';
import { getAccount, getToken } from '@/router';
import { useToast } from "primevue/usetoast";
const toast = useToast();
//操作栏可视化
const operationVisible = ref(true);
//出行方式可视化
const isWalkingVisible = ref(false);
const isBikingVisible = ref(false);
const isDrivingVisible = ref(false);
//弹窗
const twoPointHistoryVisible = ref(false); // 控制Dialog可见性
const circleHistoryVisible = ref(false);
const coolPathHistoryVisible = ref(false);
//用户
const userName = getAccount();
const token = getToken();
//地图
const map = ref(null);
const mapContainer = ref(null);
let drawCurrentPath = [[]];
let circle_drawCurrentPath = [];
const currentOperations = ref();//当前操作
const twoPointtabs = ref([]);//两点路径信息
const bike_twoPointtabs = ref([]);
const car_twoPointtabs = ref([]);
const circlePathtabs = ref([]);
let roadsLayer = null;//高亮道路

//收藏道路
let collectionPath = [];
//两点路径
const collectTwoPathVisible = ref(false);
const collectionTwoPath_info = ref();//收藏地点备注
const collectionTwoPathValue = ref(null);
//环形路径
const collectCirclePathVisible = ref(false);
const collectionCirclePath_info = ref();//收藏地点备注
const collectionCirclePathValue = ref(null);
//常用地址
const commonVisible = ref(false);
const commonPoint = [];
const commonPoint_info = ref();//收藏地点备注
//地址收藏
const visible = ref(false);//窗口可视
const collectionPoint = [];
const collectionPoint_info = ref();//收藏地点备注

//林荫道路信息路径
const greenroadsPath = '../../public/path/avenue.geojson';

//时间天气
const currentTime = ref('');
const currentWeather = ref('');
//途径点
const waypoints = ref([]);


//两点规划
let twoPointdata = null;
const twoPointHistory = ref();
//两点路径搜索
const start_end_items = [];
//起点
const selected_startItem = ref();
const filtered_startItems = ref();

const search_startItems = async (event) => {
  let query = event.query;
  let _filtered_startItems = [];
  try {
    const response = await axios.get(`http://localhost:8080/history/twoPoint/listAll?account=${encodeURIComponent(userName)}`, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token,
      }
    });
    twoPointHistory.value = toRaw(response.data);
    for (let i = 0; i < toRaw(twoPointHistory.value).length; i++) {
      start_end_items[i] = toRaw(twoPointHistory.value)[i].search_origin;
    }
    for (let i = toRaw(twoPointHistory.value).length; i < toRaw(twoPointHistory.value).length * 2; i++) {
      start_end_items[i] = toRaw(twoPointHistory.value)[i - toRaw(twoPointHistory.value).length].search_destination;
    }

    for (let i = 0; i < start_end_items.length; i++) {
      let item = start_end_items[i];
      if (item && item.toLowerCase().indexOf(query.toLowerCase()) === 0) {
        _filtered_startItems.push(item);
      }
    }

    filtered_startItems.value = _filtered_startItems;
  } catch (error) {
    if (error.response) {
      // 服务器返回响应，状态码在2xx之外
      console.error('服务器错误:', error.response.status, error.response.data);
    } else if (error.request) {
      // 请求已发出，但没有收到响应
      console.error('未收到服务器响应:', error.request);
    } else {
      // 请求设置错误
      console.error('请求设置错误:', error.message);
    }
  }
};

// 途径点搜索
const search_waypointItems = async (event, index) => {
  let query = event.query;
  let _filtered_waypointItems = [];
  try {
    const response = await axios.get(`http://localhost:8080/history/twoPoint/listAll?account=${encodeURIComponent(userName)}`, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token,
      }
    });
    const waypointsHistory = toRaw(response.data);
    for (let i = 0; i < waypointsHistory.length; i++) {
      start_end_items[i] = waypointsHistory[i].search_origin;
    }
    for (let i = waypointsHistory.length; i < waypointsHistory.length * 2; i++) {
      start_end_items[i] = waypointsHistory[i - waypointsHistory.length].search_destination;
    }

    for (let i = 0; i < start_end_items.length; i++) {
      let item = start_end_items[i];
      if (item && item.toLowerCase().indexOf(query.toLowerCase()) === 0) {
        _filtered_waypointItems.push(item);
      }
    }

    waypoints.value[index].filteredItems = _filtered_waypointItems;
  } catch (error) {
    if (error.response) {
      // 服务器返回响应，状态码在2xx之外
      console.error('服务器错误:', error.response.status, error.response.data);
    } else if (error.request) {
      // 请求已发出，但没有收到响应
      console.error('未收到服务器响应:', error.request);
    } else {
      // 请求设置错误
      console.error('请求设置错误:', error.message);
    }
  }
};

// 添加途径点
const addWaypoint = () => {
  waypoints.value.push({ selectedItem: ref(''), filteredItems: ref([]) });
};

// 删除途径点
const removeWaypoint = (index) => {
  waypoints.value.splice(index, 1);
};
//终点
const selected_endItem = ref();
const filtered_endItems = ref();
const search_endItems = (event) => {
  let query = event.query;
  let _filtered_endItems = [];

  for (let i = 0; i < start_end_items.length; i++) {
    let item = start_end_items[i];

    if (item.toLowerCase().indexOf(query.toLowerCase()) === 0) {
      _filtered_endItems.push(item);
    }
  }

  filtered_endItems.value = _filtered_endItems;
};

//环形规划
const startEnd_items = [];
const circleHistory = ref();
const selected_startEndItem = ref();
const filtered_startEndItems = ref();
const Distance = ref();//范围规划
const search_startEndItems = async (event) => {
  let query = event.query;
  let _filtered_startEndItems = [];
  try {
    const response = await axios.get(`http://localhost:8080/history/ring/listAll?account=${encodeURIComponent(userName)}`, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token,
      }
    });
    circleHistory.value = toRaw(response.data);
    console.log(circleHistory.value);
    for (let i = 0; i < toRaw(circleHistory.value).length; i++) {
      startEnd_items[i] = toRaw(circleHistory.value)[i].ring_search_location;
    }
    for (let i = 0; i < startEnd_items.length; i++) {
      let item = startEnd_items[i];
      if (item && item.toLowerCase().indexOf(query.toLowerCase()) === 0) {
        _filtered_startEndItems.push(item);
      }
    }

    filtered_startEndItems.value = _filtered_startEndItems;
  } catch (error) {
    if (error.response) {
      // 服务器返回响应，状态码在2xx之外
      console.error('服务器错误:', error.response.status, error.response.data);
    } else if (error.request) {
      // 请求已发出，但没有收到响应
      console.error('未收到服务器响应:', error.request);
    } else {
      // 请求设置错误
      console.error('请求设置错误:', error.message);
    }
  }
};
//林荫道选择
const selectedCoolPath = ref();
const coolPath = ref([]);
const synchronousData = async () => {
  selected_coolPathItem.value = toRaw(selectedCoolPath.value).tree_line_name;
  console.log(toRaw(selectedCoolPath.value).tree_line_name)
}
const search_AllcoolPathItems = async () => {
  try {
    const response = await axios.get(`http://localhost:8080/map/searchBoulevard/listAll`, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token,
      }
    });
    coolPath.value = toRaw(response.data);
    console.log(coolPath.value);
  } catch (error) {
    if (error.response) {
      // 服务器返回响应，状态码在2xx之外
      console.error('服务器错误:', error.response.status, error.response.data);
    } else if (error.request) {
      // 请求已发出，但没有收到响应
      console.error('未收到服务器响应:', error.request);
    } else {
      // 请求设置错误
      console.error('请求设置错误:', error.message);
    }
  }
};
//林荫道搜索
const coolPath_items = [];//历史记录
let coolPathdata = [];
const selected_coolPathItem = ref();
const filtered_coolPathItems = ref();
const coolPathHistory = ref();
const search_coolPathItems = async (event) => {
  let query = event.query;
  let _filtered_coolPathItems = [];
  try {
    const response = await axios.get(`http://localhost:8080/history/treeLine/listAll?account=${encodeURIComponent(userName)}`, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token,
      }
    });
    coolPathHistory.value = toRaw(response.data);
    for (let i = 0; i < toRaw(coolPathHistory.value).length; i++) {
      coolPath_items[i] = toRaw(coolPathHistory.value)[i].tree_line_name;
    }
    for (let i = 0; i < coolPath_items.length; i++) {
      let item = coolPath_items[i];
      if (item && item.toLowerCase().indexOf(query.toLowerCase()) === 0) {
        _filtered_coolPathItems.push(item);
      }
    }

    filtered_coolPathItems.value = _filtered_coolPathItems;
    console.log(filtered_coolPathItems.value)
  } catch (error) {
    if (error.response) {
      // 服务器返回响应，状态码在2xx之外
      console.error('服务器错误:', error.response.status, error.response.data);
    } else if (error.request) {
      // 请求已发出，但没有收到响应
      console.error('未收到服务器响应:', error.request);
    } else {
      // 请求设置错误
      console.error('请求设置错误:', error.message);
    }
  }
};
// 根据道路ID绘制林荫道路
const highlightRoadById = (roads) => {
  roadsLayer.eachLayer((layer) => {
    layer.setStyle({
      color: 'green', // 默认颜色
      weight: 3, // 默认宽度
    });
  });

  if (!roadsLayer) return;
  for (let i = 0; i < roads.length; i++) {
    let road = roads[i];
    roadsLayer.eachLayer((layer) => {
      if (layer.feature.properties.id === road.id.toString()) {
        layer.setStyle({ color: 'red', weight: 3 });
        let coolPathcenter = L.latLng(road.lat, road.lng);
        map.value.setView(coolPathcenter, 15);
      }
    });
  }
};
// 根据选中项高亮显示对应路径(用于高亮显示指定林荫道)
const searchCoolPath = async () => {
  try {
    const response = await axios.post('http://localhost:8080/map/searchBoulevard', {
      tree_line_name: selected_coolPathItem.value,
      account: userName
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token,
      }
    });
    console.log(response.data)
    coolPathdata = response.data;
    let selectedRoads = [];
    for (let i = 0; i < coolPathdata.length; i++) {
      if (coolPathdata[i].tree_line_name.includes(selected_coolPathItem.value)) {
        selectedRoads.push({
          id: coolPathdata[i].tree_line_id,
          lat: coolPathdata[i].tree_line_x,
          lng: coolPathdata[i].tree_line_y
        });
      }
    }
    console.log(selectedRoads)
    highlightRoadById(selectedRoads);
  } catch (error) {
    toast.add({ severity: 'error', summary: 'Error', detail: '林荫道不存在', group: 'br', life: 2000 });
    console.error('请求错误:', error);
    return [];
  }
};
//取消指定路径显示(用于林荫道取消高亮)
const resetHighlight = () => {
  if (!roadsLayer) return;

  roadsLayer.eachLayer((layer) => {
    layer.setStyle({
      color: 'green', // 默认颜色
      weight: 3, // 默认宽度
    });
  });
};
//辅助函数
const fetchTime = async () => {
  // 获取当前时间
  const now = new Date();
  currentTime.value = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); // 设置为电脑时间，格式为HH:MM
}
const fetchWeather = async () => {
  // 获取天气信息的 API
  const weatherResponse = await fetch('https://devapi.qweather.com/v7/weather/now?location=101010100&key=70abdac7a9a54812966666cd291838a9');
  const weatherData = await weatherResponse.json();
  currentWeather.value = `${weatherData.now.temp}°C, ${weatherData.now.text}`;
};
//获取详细地点信息
const getAddress = async (lat, lng) => {
  const response = await fetch(`https://restapi.amap.com/v3/geocode/regeo?output=json&location=${lng},${lat}&key=7c9e6682a07b9e58e94b9703d82e82f7&radius=100&extensions=all `);
  const data = await response.json();
  if (data.status === '1' && data.regeocode) {
    return data.regeocode.formatted_address;
  }
  return '未知地点';
};
// 通过名称获取经纬度
const getCoordinates = async (address) => {
  const response = await fetch(`https://restapi.amap.com/v3/geocode/geo?address=${address}&output=json&key=7c9e6682a07b9e58e94b9703d82e82f7`);
  const data = await response.json();
  if (data.status === '1' && data.geocodes.length > 0) {
    const location = data.geocodes[0].location.split(',');
    return {
      lng: parseFloat(location[0]),
      lat: parseFloat(location[1])
    };
  }
  return null;
};

//清空两点路径信息
const resetFields = () => {
  selected_startItem.value = '';
  selected_endItem.value = '';
  waypoints.value = []; // 将途径点设为空
  isWalkingVisible.value = false;
  isBikingVisible.value = false;
  isDrivingVisible.value = false;
  // 移除当前路径
  if (drawCurrentPath.length > 0) {
    drawCurrentPath.forEach(row => {
      row.forEach(path => {
        map.value.removeLayer(path);
      });
    });
    drawCurrentPath = [[]];
  }
};
//清空环形路径信息
const circle_resetFields = () => {
  selected_startEndItem.value = '';
  Distance.value = null;
  // 移除当前路径
  if (circle_drawCurrentPath.length > 0) {
    circle_drawCurrentPath.forEach(path => {
      map.value.removeLayer(path);
    });
    circle_drawCurrentPath = [];
  }
};
//林荫道信息清空
const cool_resetFields = () => {
  selected_coolPathItem.value = '';
  selectedCoolPath.value = '';
  resetHighlight();
};



//获取两点路径信息
const getTwoPointRoute = async (startLng, startLat, endLng, endLat, startAddress, endAddress, wayPoints, wayPointsLat, wayPointsLng) => {
  try {
    const response = await axios.post('http://localhost:8080/navigate/pointToPoint', {
      search_origin_x: startLng,
      search_origin_y: startLat,
      search_destination_x: endLng,
      search_destination_y: endLat,
      search_origin: startAddress,
      search_destination: endAddress,
      search_waypoints: wayPoints,
      search_waypoints_x: wayPointsLng,
      search_waypoints_y: wayPointsLat,
      account: userName
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token,
      }
    });

    twoPointdata = response.data;
    console.log(twoPointdata)
    const points = [[]];
    for (let i = 0; i < twoPointdata.length; i++) {
      points[i] = [];
      for (let j = 0; j < twoPointdata[i].length; j++) {
        if (twoPointdata[i][j].vehicle === "custom_foot") {
          twoPointtabs.value[j] = {
            index: j,
            type: twoPointdata[i][j].vehicle,
            title: "路线" + j,
            content: "起点: " + startAddress + "<br>终点: " + endAddress + "<br>路径长度: " + twoPointdata[i][j].length + " 米" + "<br>路径耗时: " + twoPointdata[i][j].time_ms / 60000 + "分钟",
            collection_path_origin: startAddress,
            collection_path_origin_x: startLng,
            collection_path_origin_y: startLat,
            collection_path_destination: endAddress,
            collection_path_destination_x: endLng,
            collection_path_destination_y: endLat,
            distance: twoPointdata[i][j].length,
            time: twoPointdata[i][j].time_ms,
            tree_line: twoPointdata[i][j].tree_ratio,
          }
          // console.log(twoPointtabs.value[j]);
        }
        if (twoPointdata[i][j].vehicle === "custom_bike") {
          bike_twoPointtabs.value[j] = {
            index: j,
            type: twoPointdata[i][j].vehicle,
            title: "路线" + j,
            content: "起点: " + startAddress + "<br>终点: " + endAddress + "<br>路径长度: " + twoPointdata[i][j].length + " 米" + "<br>路径耗时: " + twoPointdata[i][j].time_ms / 60000 + "分钟",
            collection_path_origin: startAddress,
            collection_path_origin_x: startLng,
            collection_path_origin_y: startLat,
            collection_path_destination: endAddress,
            collection_path_destination_x: endLng,
            collection_path_destination_y: endLat,
            distance: twoPointdata[i][j].length,
            time: twoPointdata[i][j].time_ms,
            tree_line: twoPointdata[i][j].tree_ratio,
          }
          // console.log(bike_twoPointtabs.value[j]);
        }
        if (twoPointdata[i][j].vehicle === "custom_car") {
          car_twoPointtabs.value[j] = {
            index: j,
            type: twoPointdata[i][j].vehicle,
            title: "路线" + j,
            content: "起点: " + startAddress + "<br>终点: " + endAddress + "<br>路径长度: " + twoPointdata[i][j].length + " 米" + "<br>路径耗时: " + twoPointdata[i][j].time_ms / 60000 + "分钟",
            collection_path_origin: startAddress,
            collection_path_origin_x: startLng,
            collection_path_origin_y: startLat,
            collection_path_destination: endAddress,
            collection_path_destination_x: endLng,
            collection_path_destination_y: endLat,
            distance: twoPointdata[i][j].length,
            time: twoPointdata[i][j].time_ms,
            tree_line: twoPointdata[i][j].tree_ratio,
          }
          // console.log(car_twoPointtabs.value[j])
        }
        points[i][j] = twoPointdata[i][j].points;
      }
    }
    if (twoPointdata[1].length > 0) {
      isWalkingVisible.value = true;
    }
    if (twoPointdata[2].length > 0) {
      isBikingVisible.value = true;
    }
    if (twoPointdata[0].length > 0) {
      isDrivingVisible.value = true;
    }

    console.log(points)
    return points;
  } catch (error) {
    console.error('请求错误:', error);
    return [];
  }
};

//获取环形路径信息
let circlePathdata = null;
const generateCirclePath = async (Lng, Lat, startAddress, Distance) => {
  try {
    const response = await axios.post('http://localhost:8080/navigate/circular', {
      ring_search_location: startAddress,
      ring_search_location_x: Lng,
      ring_search_location_y: Lat,
      target_distance: Distance,
      account: userName
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token,
      }
    });

    circlePathdata = response.data;
    const points = [];
    for (let i = 0; i < circlePathdata.length; i++) {
      circlePathtabs.value[i] = {
        index: i,
        title: "路线" + i,
        content: "起点: " + startAddress + "<br>路径长度: " + circlePathdata[i].length + "米" + "<br>路径耗时: " + circlePathdata[i].time_ms / 60000 + "分钟",
        collection_path_origin: startAddress,
        collection_path_origin_x: Lng,
        collection_path_origin_y: Lat,
        collection_path_destination: startAddress,
        collection_path_destination_x: Lng,
        collection_path_destination_y: Lat,
        distance: circlePathdata[i].length,
        time: circlePathdata[i].time_ms,
        tree_line: circlePathdata[i].tree_ratio,
      }

      points[i] = circlePathdata[i].points;
    }
    return points;
  } catch (error) {
    console.error('请求错误:', error);
    return [];
  }
};


//两点路径搜索
const searchTwoPoints = async () => {
  if (selected_startItem.value && selected_endItem.value) {
    const start = selected_startItem.value;
    const end = selected_endItem.value;
    let _waypoints = [];
    for (let i = 0; i < waypoints.value.length; i++) {
      _waypoints[i] = waypoints.value[i].selectedItem;
    }
    const startCoordinate = await getCoordinates(start);
    const endCoordinate = await getCoordinates(end);
    let waypointCoordinates = [];
    let wayPoints_lat = [];
    let wayPoints_lng = [];
    for (let i = 0; i < _waypoints.length; i++) {
      waypointCoordinates[i] = await getCoordinates(_waypoints[i]);
      console.log("途径点" + i + _waypoints[i] + "经纬度" + waypointCoordinates[i].lat + waypointCoordinates[i].lng)
      wayPoints_lat[i] = waypointCoordinates[i].lat;
      wayPoints_lng[i] = waypointCoordinates[i].lng;
    }
    //起终点地址名称
    const coordinates = await getTwoPointRoute(
      startCoordinate.lng,
      startCoordinate.lat,
      endCoordinate.lng,
      endCoordinate.lat,
      start,
      end,
      _waypoints,
      wayPoints_lat,
      wayPoints_lng
    );
    drawPaths(coordinates);
  }
};

//环形路径搜索
const searchCirclePoints = async () => {
  if (selected_startEndItem.value && Distance.value) {
    let coordinates = null;
    const startAddress = selected_startEndItem.value;
    const startCoordinate = await getCoordinates(startAddress);
    if (startCoordinate) {
      coordinates = await generateCirclePath(startCoordinate.lng, startCoordinate.lat, startAddress, Distance.value);
      // 移除当前路径
      if (circle_drawCurrentPath.length > 0) {
        circle_drawCurrentPath.forEach(path => {
          map.value.removeLayer(path);
        });
        circle_drawCurrentPath = [];
      }
      drawCirclePaths(coordinates);
    }
  }
};
//绘制所有道路(用于环形路径规划)
const drawCirclePaths = (coordinates) => {
  // 移除当前路径
  if (circle_drawCurrentPath.length > 0) {
    circle_drawCurrentPath.forEach(path => {
      map.value.removeLayer(path);
    });
    circle_drawCurrentPath = [];
  }
  for (let i = 0; i < coordinates.length; i++) {
    const polyline = L.polyline.antPath(coordinates[i], {
      "delay": 400,
      "dashArray": [10, 200],
      "weight": 5,
      "color": "#5349E0",
      "pulseColor": "#EBCCFF",
      "paused": false,
      "reverse": false,
      "hardwareAccelerated": true
    }).addTo(map.value);
    circle_drawCurrentPath[i] = polyline;
  }
}
//高亮绘制指定路径(用于环形路径规划)
const highlightCieclePath = (index) => {
  if (!circle_drawCurrentPath) return;
  for (let i = 0; i < circle_drawCurrentPath.length; i++) {
    if (i === index) {
      circle_drawCurrentPath[i].setStyle({ color: '#5349E0', pulseColor: "#EBCCFF" });
    } else {
      circle_drawCurrentPath[i].setStyle({ color: '#fafafa00', pulseColor: "#fafafa00" });
    }
  }
};
//绘制所有道路(用于两点路径规划)
const drawPaths = (coordinates) => {
  // 移除当前路径
  if (drawCurrentPath.length > 0) {
    drawCurrentPath.forEach(row => {
      row.forEach(path => {
        map.value.removeLayer(path);
      });
    });
    drawCurrentPath = [[]];
  }
  for (let i = 0; i < coordinates.length; i++) {
    drawCurrentPath[i] = [];
    for (let j = 0; j < coordinates[i].length; j++) {
      const polyline = L.polyline.antPath(coordinates[i][j], {
        "delay": 400,
        "dashArray": [10, 200],
        "weight": 5,
        "color": "#5349E0",
        "pulseColor": "#EBCCFF",
        "paused": false,
        "reverse": false,
        "hardwareAccelerated": true
      }).addTo(map.value);
      drawCurrentPath[i][j] = polyline;
    }
  }
}
const determineTwoPointPath = (index, type) => {
  highlightPath(index, type);
}

//高亮绘制指定路径(用于路径规划)
const highlightPath = (index, type) => {
  for (let i = 0; i < drawCurrentPath.length; i++) {
    for (let j = 0; j < drawCurrentPath[i].length; j++) {
      drawCurrentPath[i][j].setStyle({ color: '#fafafa00', pulseColor: "#fafafa00" });
    }
  }
  console.log(type + "第" + index + "号路");
  let type_index = -1;
  if (type === "custom_foot") {
    type_index = 0;
  }
  if (type === "custom_car") {
    type_index = 2;
  }
  if (type === "custom_bike") {
    type_index = 1;
  }
  if (!drawCurrentPath) return;
  console.log(drawCurrentPath)
  for (let j = 0; j < drawCurrentPath[type_index].length; j++) {
    if (j === index) {
      drawCurrentPath[type_index][j].setStyle({ color: 'blue', pulseColor: "#FF9E7B" });
      console.log(drawCurrentPath[type_index][j])
    } else {
      drawCurrentPath[type_index][j].setStyle({ color: '#fafafa00', pulseColor: "#fafafa00" });
    }
  }
};

// 加载GeoJSON数据(林荫道数据)
const loadGeoJSONData = async () => {
  const response = await fetch(greenroadsPath);
  if (!response.ok) {
    throw new Error(`Failed to load GeoJSON data: ${response.statusText}`);
  }
  return await response.json();
};


//收藏指定路径
//环形路径
let collectCirclePath_index = -1;
const _collectCirclePath = async (index) => {
  collectCirclePathVisible.value = true;
  collectCirclePath_index = index;
}

const collectCirclePath = async (index) => {
  collectionPath = toRaw(circlePathtabs.value)
  try {
    const response = await axios.post('http://localhost:8080/collections/path/add', {
      collection_path_origin: collectionPath[index].collection_path_origin,
      collection_path_origin_x: collectionPath[index].collection_path_origin_x,
      collection_path_origin_y: collectionPath[index].collection_path_origin_y,
      collection_path_destination: collectionPath[index].collection_path_destination,
      collection_path_destination_x: collectionPath[index].collection_path_destination_x,
      collection_path_destination_y: collectionPath[index].collection_path_destination_y,
      distance: collectionPath[index].distance,
      time: collectionPath[index].time,
      tree_line: collectionPath[index].tree_line,
      collection_path_info: collectionCirclePath_info.value,
      mark: collectionCirclePathValue.value,
      account: userName
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token,
      }
    });

    if (response.status === 200) {
      console.log("请求成功");
      collectCirclePathVisible.value = false
      collectionCirclePath_info.value = '';
      collectionCirclePathValue.value = '';
      toast.add({ severity: 'success', summary: 'Success Message', detail: '收藏路线成功', group: 'br', life: 2000 });
    } else {
      toast.add({ severity: 'error', summary: 'Error', detail: '收藏路线失败', group: 'br', life: 2000 });
      console.log("请求失败");
    }
  } catch (error) {
    if (error.response) {
      // 服务器返回响应，状态码在2xx之外
      console.error('服务器错误:', error.response.status, error.response.data);
    } else if (error.request) {
      // 请求已发出，但没有收到响应
      console.error('未收到服务器响应:', error.request);
    } else {
      // 请求设置错误
      console.error('请求设置错误:', error.message);
    }
  }
};
//两点路径
let collectTwoPointsPath_index = -1;
let collectType = -1;
const _collectTwoPointsPath = async (index, type) => {
  if (type === "custom_foot") {
    collectType = 0;
  }
  if (type === "custom_car") {
    collectType = 2;
  }
  if (type === "custom_bike") {
    collectType = 1;
  }
  collectTwoPathVisible.value = true;
  collectTwoPointsPath_index = index;
}

const collectTwoPointsPath = async (index, type) => {
  if (type === 0) {
    collectionPath = toRaw(twoPointtabs.value);
  }
  if (type === 2) {
    collectionPath = toRaw(car_twoPointtabs.value);
    console.log(collectionPath);
  }
  if (type === 1) {
    collectionPath = toRaw(bike_twoPointtabs.value);
  }
  try {
    const response = await axios.post('http://localhost:8080/collections/path/add', {
      collection_path_origin: collectionPath[index].collection_path_origin,
      collection_path_origin_x: collectionPath[index].collection_path_origin_x,
      collection_path_origin_y: collectionPath[index].collection_path_origin_y,
      collection_path_destination: collectionPath[index].collection_path_destination,
      collection_path_destination_x: collectionPath[index].collection_path_destination_x,
      collection_path_destination_y: collectionPath[index].collection_path_destination_y,
      distance: collectionPath[index].distance,
      time: collectionPath[index].time,
      tree_line: collectionPath[index].tree_line,
      collection_path_info: collectionTwoPath_info.value,
      mark: collectionTwoPathValue.value,
      account: userName
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token,
      }
    });

    if (response.status === 200) {
      console.log("请求成功");
      collectTwoPathVisible.value = false;
      collectionTwoPath_info.value = '';
      collectionTwoPathValue.value = '';
      toast.add({ severity: 'success', summary: 'Success Message', detail: '收藏路线成功', group: 'br', life: 2000 });
    } else {
      console.log("请求失败");
      toast.add({ severity: 'error', summary: 'Error', detail: '收藏路线失败', life: 2000 });
    }
  } catch (error) {
    if (error.response) {
      // 服务器返回响应，状态码在2xx之外
      console.error('服务器错误:', error.response.status, error.response.data);
    } else if (error.request) {
      // 请求已发出，但没有收到响应
      console.error('未收到服务器响应:', error.request);
    } else {
      // 请求设置错误
      console.error('请求设置错误:', error.message);
    }
  }
};
//常用地址
const setCommonPoint = async () => {
  try {
    const response = await axios.post('http://localhost:8080/user/addAddress', {
      user_address: commonPoint.value.user_address,
      user_address_x: commonPoint.value.user_address_x,
      user_address_y: commonPoint.value.user_address_y,
      user_address_info: commonPoint_info.value,
      account: userName
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token,
      }
    });

    if (response.status === 200) {
      console.log("请求成功");
      commonVisible.value = false;
      commonPoint_info.value = [];
      toast.add({ severity: 'success', summary: 'Success Message', detail: '常用设置成功', group: 'br', life: 2000 });
    } else {
      console.log("请求失败");
      toast.add({ severity: 'error', summary: 'Error', detail: '常用设置失败', group: 'br', life: 2000 });
    }
  } catch (error) {
    if (error.response) {
      // 服务器返回响应，状态码在2xx之外
      console.error('服务器错误:', error.response.status, error.response.data);
    } else if (error.request) {
      // 请求已发出，但没有收到响应
      console.error('未收到服务器响应:', error.request);
    } else {
      // 请求设置错误
      console.error('请求设置错误:', error.message);
    }
  }
}
//收藏地址
const collectPoint = async () => {
  try {
    const response = await axios.post('http://localhost:8080/collections/poi/add', {
      collection_location: collectionPoint.value.collection_location,
      collection_location_x: collectionPoint.value.collection_location_x,
      collection_location_y: collectionPoint.value.collection_location_y,
      collection_location_info: collectionPoint_info.value,
      account: userName
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token,
      }
    });

    if (response.status === 200) {
      console.log("请求成功");
      visible.value = false;
      collectionPoint_info.value = [];
      toast.add({ severity: 'success', summary: 'Success Message', detail: '收藏地址成功', group: 'br', life: 3000 });
    } else {
      console.log("请求失败");
      toast.add({ severity: 'error', summary: 'Error', detail: '收藏地址失败', group: 'br', life: 3000 });
    }
  } catch (error) {
    if (error.response) {
      // 服务器返回响应，状态码在2xx之外
      console.error('服务器错误:', error.response.status, error.response.data);
    } else if (error.request) {
      // 请求已发出，但没有收到响应
      console.error('未收到服务器响应:', error.request);
    } else {
      // 请求设置错误
      console.error('请求设置错误:', error.message);
    }
  }
};
//获取当前操作
const CurrentOperations = (index) => {
  currentOperations.value = index;
}
onMounted(async () => {
  map.value = L.map(mapContainer.value, {
    zoomControl: true // 禁用默认的缩放控件
  }).setView([31.2304, 121.4737], 13);

  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 19,
  }).addTo(map.value);
  let marker = L.marker([31.2304, 121.4737]).addTo(map.value).bindPopup('这里是上海市中心').openPopup();
  //显示所有林荫道
  const greenRoads = await loadGeoJSONData();
  // 将GeoJSON数据添加到地图上
  roadsLayer = L.geoJSON(greenRoads, {
    style: {
      color: 'green',
      weight: 3,
    }
  }).addTo(map.value);

  // 初始化获取天气和时间
  fetchTime();
  fetchWeather();
  //每分钟更新一次时间
  setInterval(fetchTime, 1000);
  // 每半小时更新天气
  setInterval(fetchWeather, 3600000);

  // 地图监听事件，返回点击处的经纬度
  map.value.on('click', async (e) => {
    // 点击时自动显示标记
    marker._shadow.style.display = 'block'; // 显示阴影
    marker._icon.style.display = 'block';
    //获取经纬度
    const { lat, lng } = e.latlng;
    //获得地址
    const address = await getAddress(lat, lng);
    //设置Popup
    const popupContent = document.createElement('div');
    popupContent.innerHTML = `
            <div>
                <p><strong>地点名称:</strong> ${address}</p>
                <p>经度: ${lng}<br>纬度: ${lat}</p>
                <button type="button" id="deleteButton">隐藏标记</button>
                <button type="button" id="collectButton">收藏地点</button>
                <button type="button" id="commonButton">设为常用地点</button>
                <button type="button" id="startButton">设为起点</button>
                <button type="button" id="endButton">设为终点</button>
                <button type="button" id="startEndButton">设为起终点</button>
                <button type="button" id="waypointButton">新增途径点</button>
            </div>
        `;

    marker.setLatLng([lat, lng]);
    marker.bindPopup(popupContent).openPopup();
    // 获取按钮元素
    const startButton = document.getElementById('startButton');
    const endButton = document.getElementById('endButton');
    const startEndButton = document.getElementById('startEndButton');
    startEndButton.disabled = true;
    //操作限制 环形路径
    if (currentOperations.value === 1) {
      startButton.disabled = true;
      endButton.disabled = true;
      startEndButton.disabled = false;
    }
    //点击事件
    popupContent.querySelector("#deleteButton").addEventListener("click", () => {
      marker._icon.style.display = 'none'; // 隐藏标记
      marker._shadow.style.display = 'none'; // 隐藏阴影
      marker.closePopup(); // 关闭弹出框
    });

    popupContent.querySelector("#collectButton").addEventListener("click", async () => {
      visible.value = true;//显示小窗口
      collectionPoint.value = {
        "collection_location": address,
        "collection_location_x": lng,
        "collection_location_y": lat,
      };
    });
    popupContent.querySelector("#commonButton").addEventListener("click", async () => {
      commonVisible.value = true;//显示小窗口
      commonPoint.value = {
        "user_address": address,
        "user_address_x": lng,
        "user_address_y": lat,
      };
    });
    //两点路径规划
    popupContent.querySelector("#startButton").addEventListener("click", async () => {
      // 禁用终点按钮
      endButton.disabled = true;
      selected_startItem.value = address;
      operationVisible.value = false;
    });

    popupContent.querySelector("#endButton").addEventListener("click", async () => {
      // 禁用起点按钮
      startButton.disabled = true;
      selected_endItem.value = address;
      operationVisible.value = false;
    });
    //途径点
    popupContent.querySelector("#waypointButton").addEventListener("click", async () => {
      waypoints.value.push({ selectedItem: address, filteredItems: [] });
      operationVisible.value = false;
    });
    //环形路径规划
    popupContent.querySelector("#startEndButton").addEventListener("click", async () => {
      selected_startEndItem.value = address;
      operationVisible.value = false;
    });

  });

});

//环形路径全部历史记录
const historyCircleData = ref([]); // 存储历史数据
const showCircleProducts = async () => {
  try {
    const response = await axios.get(`http://localhost:8080/history/ring/listAll?account=${encodeURIComponent(userName)}`, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token,
      }
    });
    historyCircleData.value = response.data;
    circleHistoryVisible.value = true; // 显示Dialog
  } catch (error) {
    console.error('请求错误:', error);
  }
};
// 删除单条历史记录
const deleteCircleHistoryRecord = async (record) => {
  console.log("删除第" + record.ring_search_id + "号环形路径数据");
  try {
    await axios.delete(`http://localhost:8080/history/ring/delete`, {
      data: {
        ring_search_id: record.ring_search_id,
      },
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token,
      }
    });
    showCircleProducts();
    toast.add({ severity: 'success', summary: 'Success Message', detail: '删除成功', group: 'br', life: 2000 });
  } catch (error) {
    console.error('删除错误:', error);
    toast.add({ severity: 'error', summary: 'Error', detail: '删除失败', group: 'br', life: 2000 });
  }
};

// 清空所有历史记录
const clearCircleHistory = async () => {
  console.log(userName + "执行环形路径数据清空");
  try {
    await axios.delete(`http://localhost:8080/history/ring/deleteAll`, {
      data: {
        account: userName
      },
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token,
      }
    });
    historyCircleData.value = [];
    toast.add({ severity: 'success', summary: 'Success Message', detail: '清空成功', group: 'br', life: 2000 });
  } catch (error) {
    console.error('清空错误:', error);
    toast.add({ severity: 'error', summary: 'Error', detail: '清空失败', group: 'br', life: 2000 });
  }
};
//两点路径全部搜索记录
const historyTwoPointData = ref([]); // 存储历史数据
const showtwoPointProducts = async () => {
  try {
    const response = await axios.get(`http://localhost:8080/history/twoPoint/listAll?account=${encodeURIComponent(userName)}`, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token,
      }
    });
    historyTwoPointData.value = response.data;
    twoPointHistoryVisible.value = true; // 显示Dialog
  } catch (error) {
    console.error('请求错误:', error);
  }
};
// 删除单条历史记录
const deletetwoPointHistoryRecord = async (record) => {
  console.log("删除第" + record.two_points_search_id + "号两点路径数据")
  try {
    await axios.delete(`http://localhost:8080/history/twoPoint/delete`, {
      data: {
        two_points_search_id: record.two_points_search_id,
      },
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token,
      }
    });
    showtwoPointProducts();
    toast.add({ severity: 'success', summary: 'Success Message', detail: '删除成功', group: 'br', life: 2000 });
  } catch (error) {
    console.error('删除错误:', error);
    toast.add({ severity: 'error', summary: 'Error', detail: '删除失败', group: 'br', life: 2000 });
  }
};

// 清空所有历史记录
const cleartwoPointHistory = async () => {
  console.log(userName + "执行两点路径数据清空");
  try {
    await axios.delete(`http://localhost:8080/history/twoPoint/deleteAll`, {
      data: {
        account: userName
      },
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token,
      }
    });
    historyTwoPointData.value = [];
    toast.add({ severity: 'success', summary: 'Success Message', detail: '清空成功', group: 'br', life: 2000 });
  } catch (error) {
    console.error('清空错误:', error);
    toast.add({ severity: 'error', summary: 'Error', detail: '清空失败', group: 'br', life: 2000 });
  }
};
//林荫道全部搜索记录
const historyCoolPathData = ref([]); // 存储历史数据
const showCoolPathProducts = async () => {
  try {
    const response = await axios.get(`http://localhost:8080/history/treeLine/listAll?account=${encodeURIComponent(userName)}`, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token,
      }
    });
    historyCoolPathData.value = response.data;
    coolPathHistoryVisible.value = true; // 显示Dialog
  } catch (error) {
    console.error('请求错误:', error);
  }
};
// 删除单条历史记录
const deleteCoolPathHistoryRecord = async (record) => {
  console.log("删除第" + record.tree_line_search_id + "号林荫道数据")
  try {
    await axios.delete(`http://localhost:8080/history/treeLine/delete`, {
      data: {
        tree_line_search_id: record.tree_line_search_id,
      },
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token,
      }
    });
    showCoolPathProducts();
    toast.add({ severity: 'success', summary: 'Success Message', detail: '删除成功', group: 'br', life: 2000 });
  } catch (error) {
    console.error('删除错误:', error);
    toast.add({ severity: 'error', summary: 'Error', detail: '删除失败', group: 'br', life: 2000 });
  }
};

// 清空所有历史记录
const clearCoolPathHistory = async () => {
  console.log(userName + "执行林荫道数据清空");
  try {
    await axios.delete(`http://localhost:8080/history/treeLine/deleteAll`, {
      data: {
        account: userName
      },
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token,
      }
    });
    historyCoolPathData.value = [];
    toast.add({ severity: 'success', summary: 'Success Message', detail: '清空成功', group: 'br', life: 2000 });
  } catch (error) {
    console.error('清空错误:', error);
    toast.add({ severity: 'error', summary: 'Error', detail: '清空失败', group: 'br', life: 2000 });
  }
};
</script>

<template>
  <div class="layout-map-container">
    <Toast position="bottom-right" group="br" />
    <div id="map" ref="mapContainer"></div>
    <div class="panel-container">
      <Panel header="操作" toggleable v-model:collapsed="operationVisible">
        <p class="operations">
          <TabView v-model:activeIndex="active" @click="CurrentOperations(active)">
            <TabPanel header="起终点规划">
              <div class="start-end">
                <div class="start">
                  <i class="pi pi-circle-fill" style="color: #00af577f"></i>
                  <FloatLabel>
                    <AutoComplete v-model="selected_startItem" :suggestions="filtered_startItems"
                      @complete="search_startItems" :virtualScrollerOptions="{ itemSize: 38 }" dropdown />
                    <label for="start">起点</label>
                  </FloatLabel>
                </div>
                <div class="waypoints">
                  <div v-for="(waypoint, index) in waypoints" :key="index" class="waypoint">
                    <Button icon="pi pi-trash" class="p-button-rounded" @click="removeWaypoint(index)" />
                    <FloatLabel>
                      <AutoComplete v-model="waypoint.selectedItem" :suggestions="waypoint.filteredItems"
                        @complete="(e) => search_waypointItems(e, index)" :virtualScrollerOptions="{ itemSize: 38 }"
                        style="width: 235px;" dropdown />
                      <label :for="'waypoint-' + index">途径点 {{ index + 1 }}</label>
                    </FloatLabel>
                  </div>
                </div>
                <div class="end">
                  <i class="pi pi-circle-fill" style="color: #ffa39e"></i>
                  <FloatLabel>
                    <AutoComplete v-model="selected_endItem" :suggestions="filtered_endItems"
                      @complete="search_endItems" :virtualScrollerOptions="{ itemSize: 38 }" dropdown />
                    <label for="end">终点</label>
                  </FloatLabel>
                </div>
                <div class="buttons">
                  <Button label="搜索" icon="pi pi-search" style="width: 120.33px;" @click="searchTwoPoints" />
                  <Button label="历史记录" icon="pi pi-warehouse" style="width: 120.33px;" @click="showtwoPointProducts" />
                  <Toast />
                  <DynamicDialog />
                </div>
                <div class="functionButtons">
                  <Button label="重置" icon="pi pi-refresh" style="width: 120.33px;" @click="resetFields" />
                  <Button label="添加途径点" icon="pi pi-plus" @click="addWaypoint" />
                </div>
                <Accordion class="transport">
                  <AccordionTab header="🚶‍步行" v-if="isWalkingVisible">
                    <p class="m-0">
                      <TabView>
                        <TabPanel v-for="tab in twoPointtabs" :key="tab.title" :header="tab.title">
                          <p class="m-0" v-html="tab.content"></p>
                          <div class="twoPointTabButtons">
                            <Button label="确认路径" icon="pi pi-check"
                              @click="determineTwoPointPath(tab.index, tab.type)" />
                            <Button label="收藏路径" icon="pi pi-star"
                              @click="_collectTwoPointsPath(tab.index, tab.type)" />
                          </div>
                        </TabPanel>
                      </TabView>
                    </p>
                  </AccordionTab>
                  <AccordionTab header="🚲骑行" v-if="isBikingVisible">
                    <p class="m-0">
                      <TabView>
                        <TabPanel v-for="tab in bike_twoPointtabs" :key="tab.title" :header="tab.title">
                          <p class="m-0" v-html="tab.content"></p>
                          <div class="twoPointTabButtons">
                            <Button label="确认路径" icon="pi pi-check"
                              @click="determineTwoPointPath(tab.index, tab.type)" />
                            <Button label="收藏路径" icon="pi pi-star"
                              @click="_collectTwoPointsPath(tab.index, tab.type)" />
                          </div>
                        </TabPanel>
                      </TabView>
                    </p>
                  </AccordionTab>
                  <AccordionTab header="🚗汽车" v-if="isDrivingVisible">
                    <p class="m-0">
                      <TabView>
                        <TabPanel v-for="tab in car_twoPointtabs" :key="tab.title" :header="tab.title">
                          <p class="m-0" v-html="tab.content"></p>
                          <div class="twoPointTabButtons">
                            <Button label="确认路径" icon="pi pi-check"
                              @click="determineTwoPointPath(tab.index, tab.type)" />
                            <Button label="收藏路径" icon="pi pi-star"
                              @click="_collectTwoPointsPath(tab.index, tab.type)" />
                          </div>
                        </TabPanel>
                      </TabView>
                    </p>
                  </AccordionTab>
                </Accordion>
              </div>
            </TabPanel>
            <TabPanel header="环形规划">
              <div class="circle">
                <div class="startEnd">
                  <i class="pi pi-circle-fill" style="color: #00af577f"></i>
                  <FloatLabel>
                    <AutoComplete v-model="selected_startEndItem" :suggestions="filtered_startEndItems"
                      @complete="search_startEndItems" :virtualScrollerOptions="{ itemSize: 38 }" dropdown />
                    <label for="startEnd">起终点</label>
                  </FloatLabel>
                </div>
                <div class="path-range">
                  <div class="distance-buttons">
                    <i class="pi pi-circle-fill" style="color:#6FD8D6"></i>
                    <FloatLabel>
                      <InputNumber v-model="Distance" inputId="distance-buttons" mode="decimal" />
                      <label for="min-buttons">路径路程</label>
                    </FloatLabel>
                  </div>
                </div>
                <div class="buttons">
                  <Button label="搜索" icon="pi pi-search" @click="searchCirclePoints" />
                  <Button label="重置" icon="pi pi-refresh" @click="circle_resetFields" />
                  <Button label="历史记录" icon="pi pi-warehouse" @click="showCircleProducts" />
                </div>
                <TabView>
                  <TabPanel v-for="tab in circlePathtabs" :key="tab.title" :header="tab.title">
                    <p class="m-1" v-html="tab.content"></p>
                    <div class="circlePathTabButtons">
                      <Button label="确认路径" icon="pi pi-check" @click="highlightCieclePath(tab.index)" />
                      <Button label="收藏路径" icon="pi pi-star" @click="_collectCirclePath(tab.index)" />
                    </div>
                  </TabPanel>
                </TabView>
              </div>
            </TabPanel>
            <TabPanel header="林荫道搜索">
              <div class="cool-path">
                <div class="cool-path-search">
                  <FloatLabel>
                    <AutoComplete v-model="selected_coolPathItem" :suggestions="filtered_coolPathItems"
                      @complete="search_coolPathItems" :virtualScrollerOptions="{ itemSize: 38 }" dropdown />
                    <label for="coolPath">林荫道搜索</label>
                  </FloatLabel>
                </div>
                <Dropdown v-model="selectedCoolPath" :options="coolPath" optionLabel="tree_line_name"
                  placeholder="林荫道选择" class="selectCoolPath" @click="search_AllcoolPathItems" @change="synchronousData">
                  <template #option="slotProps">
                    <div class="flex align-items-center">
                      <div>{{ slotProps.option.tree_line_name }}</div>
                    </div>
                  </template>
                  <template #footer>
                    <div class="py-2 px-3">
                      <b>{{ selectedCoolPath ? 1 : 0 }}</b> item selected.
                    </div>
                  </template>
                </Dropdown>
                <div class="buttons">
                  <Button label="搜索" icon="pi pi-search" @click="searchCoolPath" />
                  <Button label="重置" icon="pi pi-refresh" @click="cool_resetFields" />
                  <Button label="历史记录" icon="pi pi-warehouse" @click="showCoolPathProducts" />
                </div>
              </div>
            </TabPanel>
          </TabView>
        </p>
      </Panel>
    </div>
    //收藏地址
    <Dialog v-model:visible="visible" modal header="备注设置" :style="{ width: '25rem' }">
      <span class="p-text-secondary block mb-5">设置你的地点备注信息</span>
      <div class="flex align-items-center gap-3 mb-3">
        <label for="collectionPoint_info" class="font-semibold w-6rem">收藏备注</label>
        <InputText id="collectionPoint_info" v-model="collectionPoint_info" class="flex-auto" autocomplete="off" />
      </div>
      <div class="flex justify-content-end gap-2">
        <Button type="button" label="取消" @click="visible = false"></Button>
        <Button type="button" label="确定收藏" @click="collectPoint"></Button>
      </div>
    </Dialog>
    //常用地址
    <Dialog v-model:visible="commonVisible" modal header="备注设置" :style="{ width: '25rem' }">
      <span class="p-text-secondary block mb-5">设置你的地点备注信息</span>
      <div class="flex align-items-center gap-3 mb-3">
        <label for="commonPoint_info" class="font-semibold w-6rem">常用备注</label>
        <InputText id="commonPoint_info" v-model="commonPoint_info" class="flex-auto" autocomplete="off" />
      </div>
      <div class="flex justify-content-end gap-2">
        <Button type="button" label="取消" @click="commonVisible = false"></Button>
        <Button type="button" label="设为常用" @click="setCommonPoint"></Button>
      </div>
    </Dialog>
    //收藏道路
    //两点路径
    <Dialog v-model:visible="collectTwoPathVisible" modal header="备注设置" :style="{ width: '25rem' }">
      <span class="p-text-secondary block mb-5">设置你的路线备注信息</span>
      <div class="flex align-items-center gap-3 mb-3">
        <label for="collectionTwoPath_info" class="font-semibold w-6rem">收藏备注</label>
        <InputText id="collectionTwoPath_info" v-model="collectionTwoPath_info" class="flex-auto" autocomplete="off" />
      </div>
      <div class="card flex justify-content-center">
        <Rating v-model="collectionTwoPathValue" :cancel="false" />
      </div>
      <div class="flex justify-content-end gap-2">
        <Button type="button" label="确定收藏"
          @click="collectTwoPointsPath(collectTwoPointsPath_index, collectType)"></Button>
        <Button type="button" label="返回" @click="collectTwoPathVisible = false"></Button>
      </div>
    </Dialog>
    //环形路径
    <Dialog v-model:visible="collectCirclePathVisible" modal header="备注设置" :style="{ width: '25rem' }">
      <span class="p-text-secondary block mb-5">设置你的路线备注信息</span>
      <div class="flex align-items-center gap-3 mb-3">
        <label for="collectionCirclePath_info" class="font-semibold w-6rem">收藏备注</label>
        <InputText id="collectionCirclePath_info" v-model="collectionCirclePath_info" class="flex-auto"
          autocomplete="off" />
      </div>
      <div class="card flex justify-content-center">
        <Rating v-model="collectionCirclePathValue" :cancel="false" />
      </div>
      <div class="flex justify-content-end gap-2">
        <Button type="button" label="确定收藏" @click="collectCirclePath(collectCirclePath_index, collectType)"></Button>
        <Button type="button" label="返回" @click="collectCirclePathVisible = false"></Button>
      </div>
    </Dialog>
    //历史记录
    //两点路径
    <Dialog v-model:visible="twoPointHistoryVisible" header="两点路径历史记录" :style="{ width: '50vw' }" maximizable modal
      :contentStyle="{ height: '300px' }">
      <DataTable :value="historyTwoPointData" scrollable scrollHeight="flex" tableStyle="min-width: 50rem">
        <Column field="search_origin" header="起点"></Column>
        <Column field="search_destination" header="终点"></Column>
        <Column header="操作">
          <template #body="slotProps">
            <Button icon="pi pi-trash" class="p-button-danger p-button-rounded"
              @click="deletetwoPointHistoryRecord(slotProps.data)" />
          </template>
        </Column>
      </DataTable>
      <template #footer>
        <Button label="清空所有历史记录" icon="pi pi-times" class="p-button-danger" @click="cleartwoPointHistory" />
        <Button label="Ok" icon="pi pi-check" @click="twoPointHistoryVisible = false" />
      </template>
    </Dialog>
    //环形路径
    <Dialog v-model:visible="circleHistoryVisible" header="两点路径历史记录" :style="{ width: '50vw' }" maximizable modal
      :contentStyle="{ height: '300px' }">
      <DataTable :value="historyCircleData" scrollable scrollHeight="flex" tableStyle="min-width: 50rem">
        <Column field="ring_search_location" header="起点"></Column>
        <Column field="target_distance" header="期望路程"></Column>
        <Column header="操作">
          <template #body="slotProps">
            <Button icon="pi pi-trash" class="p-button-danger p-button-rounded"
              @click="deleteCircleHistoryRecord(slotProps.data)" />
          </template>
        </Column>
      </DataTable>
      <template #footer>
        <Button label="清空所有历史记录" icon="pi pi-times" class="p-button-danger" @click="clearCircleHistory" />
        <Button label="Ok" icon="pi pi-check" @click="circleHistoryVisible = false" />
      </template>
    </Dialog>
    //林荫道
    <Dialog v-model:visible="coolPathHistoryVisible" header="两点路径历史记录" :style="{ width: '50vw' }" maximizable modal
      :contentStyle="{ height: '300px' }">
      <DataTable :value="historyCoolPathData" scrollable scrollHeight="flex" tableStyle="min-width: 50rem">
        <Column field="tree_line_name" header="道路名称"></Column>
        <Column header="操作">
          <template #body="slotProps">
            <Button icon="pi pi-trash" class="p-button-danger p-button-rounded"
              @click="deleteCoolPathHistoryRecord(slotProps.data)" />
          </template>
        </Column>
      </DataTable>
      <template #footer>
        <Button label="清空所有历史记录" icon="pi pi-times" class="p-button-danger" @click="clearCoolPathHistory" />
        <Button label="Ok" icon="pi pi-check" @click="coolPathHistoryVisible = false" />
      </template>
    </Dialog>
    <div id="info-box" class="info-box">
      <p>时间: {{ currentTime }}</p>
      <p>天气: {{ currentWeather }}</p>
    </div>
  </div>
</template>
